import React, { useEffect, useState } from 'react';
import MyOrder from './index';
import {List, Card, Tag, Modal} from 'antd';
import './index.css';
import {useNavigate} from "react-router-dom";

const orders = [
    { orderId: '3', productList: ['空调  强劲制冷 | 高效节能 | 智能互联'], productImage:'https://cdn.cnbj0.fds.api.mi-img.com/b2c-shopapi-pms/75430C54AC5944E773D050D1B69DBAB3.jpg', cost: 1890, status: '待收货' },
];

const statusToColor = {
    '待付款': 'purple',
    '售后': 'red',
    '待收货': 'blue',
    '已完成': 'green',
};

const OrderToReceive = () => {
    const [orders, setOrders] = useState([]);
    const [confirmModalVisible, setConfirmModalVisible] = useState(false);
    const [orderIdToDelete, setOrderIdToDelete] = useState(null);

    const handleDeleteConfirmation = (orderId) => {
        setOrderIdToDelete(orderId);
        setConfirmModalVisible(true);
    };

    const handleConfirmDelete = () => {
        deleteOrder(orderIdToDelete);
        setOrderIdToDelete(null);
        setConfirmModalVisible(false);
    };

    const handleCancelDelete = () => {
        setOrderIdToDelete(null);
        setConfirmModalVisible(false);
    };

    const deleteOrder = (orderId) => {
        try {
            const orderList = JSON.parse(localStorage.getItem('orderList'));
            const updatedOrderList = orderList.filter(order => order.orderId !== orderId);
            localStorage.setItem('orderList', JSON.stringify(updatedOrderList));
            const ordersToPay = updatedOrderList.filter(order => order.status === '待收货');
            setOrders(ordersToPay);
        } catch (error) {
            console.error('Error deleting order:', error);
        }
    };

    const changeOrderInfo = (orderId) => {
        try {
            const orderList = JSON.parse(localStorage.getItem('orderList'));
            const foundOrder = orderList.find(order => order.orderId === Number(orderId));
            if (foundOrder) {
                foundOrder.status = '已完成';
                localStorage.setItem('orderList', JSON.stringify(orderList));
                const ordersToPay = orderList.filter(order => order.status === '待收货');
                setOrders(ordersToPay);
            } else {
                console.log('Order not found with id:', orderId);
            }
        } catch (error) {
            console.error('Error fetching order info:', error);
        }
    };

    useEffect(() => {
        const fetchOrders = () => {
            const orderData = JSON.parse(localStorage.getItem('orderList') || '[]');
            const ordersToPay = orderData.filter(order => order.status === '待收货');
            setOrders(ordersToPay);
        };

        fetchOrders();

        const handleStorageChange = () => {
            fetchOrders();
        };

        window.addEventListener('storage', handleStorageChange);

        return () => {
            window.removeEventListener('storage', handleStorageChange);
        };
    }, []);

    const navigate = useNavigate();
    const gotoDetail = (orderId) => {
        navigate('/order/info/' + orderId);
    };

    return (
        <MyOrder>
            <List
                grid={{ gutter: 16, column: 1 }}
                dataSource={orders}
                renderItem={order => (
                    <List.Item>
                        <Card title={
                            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <span onClick={() => gotoDetail(order.orderId)}>订单ID: {order.orderId}</span>
                                <Tag color={statusToColor[order.status]}>{order.status}</Tag>
                            </div>
                        }>
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <div>
                                    {order.productList.map((product, index) => (
                                        <div key={index}>
                                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                                <img src={product.details[0]} className="order-image" style={{ marginRight: 10 }} />
                                                <List.Item style={{ display: 'flex', alignItems: 'center' }}>
                                                    <span style={{fontSize: '17px', fontWeight:'bold', flex: 1}}>{product.productName}</span>
                                                </List.Item>
                                                <List.Item style={{ display: 'flex', alignItems: 'center' }}>
                                                    <span style={{fontSize: '17px'}}>￥{product.price}</span>
                                                </List.Item>
                                                <List.Item style={{ display: 'flex', alignItems: 'center' }}>
                                                    <span style={{fontSize: '14px'}}>x{product.count}</span>
                                                </List.Item>
                                            </div>
                                        </div>
                                    ))}
                                    <List.Item style={{ display: 'flex', justifyContent: 'flex-end'}}>
                                        {'实付款 ：'}
                                        <span style={{fontSize: '20px',fontWeight:'bold',color:'#ff5e62'}}>￥{order.cost+order.shipping-order.discount}</span>
                                    </List.Item>
                                    <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                                        <button className="order-button-delete" onClick={() => handleDeleteConfirmation(order.orderId)}>删除订单</button>
                                        <button className="order-button-buy" onClick={() => changeOrderInfo(order.orderId)}>确认收货</button>
                                    </div>
                                </div>
                            </div>
                        </Card>
                    </List.Item>
                )}
            />
            <Modal
                title="确认删除订单"
                open={confirmModalVisible}
                onOk={handleConfirmDelete}
                onCancel={handleCancelDelete}
                footer={[
                    <button key="back" className="order-button-delete" onClick={handleCancelDelete}>
                        取消
                    </button>,
                    <button key="submit" className="order-button-buy" type="primary" onClick={handleConfirmDelete}>
                        确认
                    </button>]}
            >
                <p>您确定要删除此订单吗？</p>
            </Modal>
        </MyOrder>
    );
};

export default OrderToReceive;
